﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace Utils
{
    public static class Extensions
    {
        public static T GetData<T>(this string data, string key)
        {
            try
            {
                var dic = JsonConvert.DeserializeObject<Dictionary<string, T>>(data);

                var state = dic.TryGetValue(key, out T value);
                return state ? value : default(T);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
        public static string GetData(this string data, string key)
        {
            return GetData<string>(data,key);
        }


        public static string SetData<T>(this string data, string key, T value)
        {
            var dic = new Dictionary<string, T>();
            try
            {
                 dic = JsonConvert.DeserializeObject<Dictionary<string, T>>(data);
            }
            catch (Exception)
            {

            }

           
            if (dic.ContainsKey(key))
            {
                dic[key] = value;
            }
            else
            {
                dic.Add(key, value);
            }

            return JsonConvert.SerializeObject(dic);

        }
        public static string SetData(this string data, string key, string value)
        {
            return SetData<string>(data, key, value);
        }
    }
}
